<?php
/**
 * Created by 2019/4/13 0013
 * Effect: TokenValidationMiddleware.php
 * Author: 品花
 * Date: 2019/4/13 0013
 * Time: 上午 10:37
 */

namespace App\Middleware;
use App\Utility\Response;
use EasySwoole\EasySwoole\Config;

class SignValidationMiddleware
{
    protected static $instance;

    public static function getInstance()
    {
        if ( !isset(self::$instance)) {
            self::$instance = new static();
        }
        return self::$instance;
    }

    public function verification($request)
    {
        $sign = $request->getRequestParam('sign');
        $token = $request->getRequestParam('token');
        $path    = $request->getUri()->getPath();
        if($path == "/"){
            return  true;
        }
        $routes  = Config::getInstance()->getConf('pass_sign_route');

        //当前路由是否需要验证签名
        if(!in_array($path,$routes)) {

            if (!$sign) {
                Response::responseJson(1004);
                return false;
            }

            //验证签名是否正确
            $params = $request->getRequestParam();
            $token  = $params['token'];

            $res = $this->verifySign_($params, $token);
            if (!$res) {
                Response::responseJson(1000);
                return false;
            }
        }

            return true;

    }


    /**
     * 验证签名
     * @param $data
     * @param $secret
     * @return bool
     * @author 品花
     * @date 2019/4/25 0025 下午 4:16
     */
    function verifySign_($data,$secret){

        $salt = Config::getInstance()->getConf('salt');

        $requestSign = $data['sign'];

        unset($data['sign']);
        unset($data['token']);

        ksort($data);

        $params = http_build_query($data);

        $sign =  strtoupper(md5(md5(urldecode($params) . $secret .$salt)));
        var_dump($sign);
//        var_dump(urldecode($params) . $secret .$salt);
        if($sign == $requestSign){
            return true;
        }else{
            return false;
        }
    }


    function getSign($data,$token){
        unset($data['token']);
        unset($data['sign']);
        $salt = Config::getInstance()->getConf('salt');
        ksort($data);

        $params = http_build_query($data);
//        var_dump(urldecode($params) . $token .$salt);
        $sign =  strtoupper(md5(md5(urldecode($params) . $token .$salt)));

        return $sign ;
    }
}

